﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace CallSignAnalysis
{
    public partial class FmQrzSynchronizePage : Form
    {
        bool INIT_PWD = false;

        public FmQrzSynchronizePage()
        {
            InitializeComponent();

            RWini.SetPath(g.lang + ".ini");
            getControlFromName(this);
        }
        private string LangReplace(string origin, string QrzSyncPage)
        {
            if (g.lang != "简体中文")
            {
                RWini.SetPath(g.lang + ".ini");
                origin = RWini.ReadValue("QrzSyncPage", QrzSyncPage);

            }
            return origin;
        }

        /// <summary>
        /// 递归方法,获取指定controlName的控件;如果控件未找到,则返回null,请注意判断null
        /// </summary>
        /// <param name="container">容器控件,可以是窗体form,也可以是panel,GroupBox等</param>
        /// <param name="controlName">控件名称</param>
        /// <returns>返回一个控件类型</returns>
        private Control getControlFromName(Control container)
        {
            foreach (Control c in container.Controls)
            {
                if (c is Sunny.UI.UIButton || c is Sunny.UI.UICheckBox || c is Sunny.UI.UILabel || c is Button)
                {
                    string t = RWini.ReadValue(c.Name, "Text");
                    if (!string.IsNullOrWhiteSpace(t))
                    {
                        c.Text = t;
                        string name = RWini.ReadValue(c.Name, "Font");
                        int size = RWini.ReadInt(c.Name, "Size", 16);
                        string Sizes = RWini.ReadValue(c.Name, "Size");
                        int.TryParse(Sizes, out size);
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            FontFamily ff = new FontFamily(name);
                            FontStyle style = FontStyle.Bold;
                            // style |= FontStyle.Regular;
                            // style |= FontStyle.Italic;, GraphicsUnit.World
                            c.Font = new Font(ff, size, style);
                        }

                    }
                }
                if (c.HasChildren)
                {
                    //这里不能直接写return  getControlFromName(c, controlName);因为会导致只执行第一个子容器控件,如果未找到就提前返回了Null;
                    Control myControl = getControlFromName(c);
                    if (myControl != null)
                    {
                        return myControl;
                    }
                }
            }
            //并非所有的代码路径都返回值,未找到就返回null
            return null;
        }
        private void FmQrzSynchronizePage_Load(object sender, EventArgs e)
        {
            //ReadPasswordFromConfig("config.yml", tbox_lotw_pwd);

            var keys = Environment.UserName;
            RSASecurity.RSAKey = keys;

            // 读取
            RWini.SetPath("config.ini");
            tbox_qrz_pwd.Text = RSASecurity.DecryptRSA(RWini.ReadValue("sync", "qrz_pwd"));
            tbox_lotw_pwd.Text = RSASecurity.DecryptRSA(RWini.ReadValue("sync", "lotw"));
            tbox_callsign.Text = RWini.ReadValue("sync", "callsign");
            string qmode = RWini.ReadValue("sync", "qmode"); if(qmode == "true") { cbox_Q_Mode.Checked = true; }

            INIT_PWD = true;

            tbox_lotw_pwd.Watermark = LangReplace("LOTW密码", "lotwpwd");
        }

        //static void ReadPasswordFromConfig(string filePath, UITextBox textBox)
        //{
        //    if (File.Exists(filePath))
        //    {
        //        // 读取yaml文件内容
        //        string fileContent = File.ReadAllText(filePath);

        //        // 反序列化yaml为对象
        //        var deserializer = new DeserializerBuilder().Build();
        //        dynamic yamlObject = deserializer.Deserialize(fileContent);

        //        // 提取密码部分并赋值给文本框
        //        if (yamlObject != null)
        //        {
        //            string password = yamlObject["lotw_pwd"];
        //            password = password.Replace("\"", "");
        //            textBox.Text = password;
        //        }
        //    }
        //}

        private void btn_cfm_pwd_Click(object sender, EventArgs e)
        {
            //if (!string.IsNullOrEmpty(tbox_lotw_pwd.Text))
            //{
            //    WritePasswordToConfig(tbox_lotw_pwd.Text);
            //    tbox_lotw_pwd.FillColor = Color.White;
            //    btn_cfm_pwd.Enabled = false;
            //}
            //else
            //{
            //    MessageBox.Show("密码不能为空，请输入密码后再保存。");
            //}
            
            if (!string.IsNullOrEmpty(tbox_callsign.Text)|| !string.IsNullOrEmpty(tbox_qrz_pwd.Text)|| !string.IsNullOrEmpty(tbox_lotw_pwd.Text))
            {
                var keys = Environment.UserName;
                RSASecurity.RSAKey = keys;
                string tbox_qrz_pwd_result = RSASecurity.EncryptRSA(tbox_qrz_pwd.Text);
                string tbox_lotw_pwd_result = RSASecurity.EncryptRSA(tbox_lotw_pwd.Text);
                string tbox_callsign_result = tbox_callsign.Text;

                // 储存
                RWini.SetPath("config.ini");
                RWini.WriteValue("sync", "qrz_pwd", tbox_qrz_pwd_result);
                RWini.WriteValue("sync", "lotw", tbox_lotw_pwd_result);
                RWini.WriteValue("sync", "callsign", tbox_callsign_result);

                tbox_lotw_pwd.FillColor = Color.White;
                btn_cfm_pwd.Enabled = false;
            }
            else
            {
                MessageBox.Show("密码不能为空，请输入密码后再保存。");
            }
        }

        //static void WritePasswordToConfig(string password)
        //{
        //    //在密码两侧加上双引号
        //    password = "\"" + password + "\"";

        //    // 序列化密码部分为yaml格式
        //    var serializer = new SerializerBuilder().DisableAliases().Build();
        //    string yaml = serializer.Serialize(new { lotw_pwd = password });

        //    yaml = yaml.Replace("'", "");

        //    // 写入yaml内容到文件
        //    File.WriteAllText("config.yml", yaml);
        //}

        private void smr_confirm_Click(object sender, EventArgs e)
        {
            //if (tbox_lotw_pwd.Text != "" && btn_cfm_pwd.Enabled == false)
            //{
            //    string filePath = "qrz_auto_import_from_lotw.exe";

            //    try
            //    {
            //        Process.Start(filePath);
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine("Error opening file: " + ex.Message);
            //    }
            //    this.DialogResult = DialogResult.OK; // 设置窗口的DialogResult为OK
            //    this.Close(); // 关闭窗口
            //}
            //else
            //{
            //    tbox_lotw_pwd.FillColor = Color.Red;
            //}

            if (tbox_lotw_pwd.Text != "" && tbox_callsign.Text != "" && tbox_qrz_pwd.Text != "" && btn_cfm_pwd.Enabled == false) 
            {

                string qMode = "";
                if (cbox_Q_Mode.Checked)
                {
                    RWini.WriteValue("sync", "qmode", "true");
                    qMode = " --silent";
                }
                else
                {
                    RWini.WriteValue("sync", "qmode", "false");
                }

                string filePath = "qrz_auto_import_from_lotw.exe";
                string arguments = tbox_callsign.Text + " " + tbox_qrz_pwd.Text + " --lotw_pwd " + tbox_lotw_pwd.Text + qMode; // 设置需要传递的参数

                try
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = filePath;
                    startInfo.Arguments = arguments;

                    Process.Start(startInfo);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error opening file: " + ex.Message);
                }

                this.DialogResult = DialogResult.OK; // 设置窗口的DialogResult为OK
                this.Close(); // 关闭窗口
            }
            else
            {
                tbox_lotw_pwd.FillColor = Color.Red;
            }
          
        }

        private void smr_close_Click(object sender, EventArgs e)
        {
            if (cbox_Q_Mode.Checked)
            {
                RWini.WriteValue("sync", "qmode", "true");
            }
            else
            {
                RWini.WriteValue("sync", "qmode", "false");
            }

            this.DialogResult = DialogResult.Cancel; // 设置窗口的DialogResult为Cancel
            this.Close(); // 关闭窗口
        }

        private void tbox_lotw_pwd_TextChanged(object sender, EventArgs e)
        {
            if (INIT_PWD)
            {
                tbox_lotw_pwd.FillColor = Color.Red;
                btn_cfm_pwd.Enabled = true;
            }
        }
    }
}
